<template>
  <el-form ref="postForm" :model="postForm" :rules="rules">
    <sticky :class-name="'sub-navbar'">
      <el-button v-if="!isEdit" @click="showGuide">显示帮助</el-button>
      <el-button
        v-loading="loading"
        type="success"
        style="margin-left: 10px"
        @click="submitForm"
      >
        {{ isEdit ? '编辑用户' : '新增用户' }}
      </el-button>
    </sticky>
    <div class="detail-container">
      <el-row>
        <warning />
        <el-col :span="24">
              <el-form-item prop="username" label="用户名：" :label-width="labelWidth" >
                <el-input
                  v-model="postForm.username"
                  placeholder="用户名"
                  :disabled="isEdit"
                />
              </el-form-item>          
              <el-form-item prop="role" label="用户类别：" :label-width="labelWidth" v-show="!roleShow">
                <el-select v-model="postForm.role" placeholder="请选择" clearable>
                   <el-option
                      v-for="item in post_options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>  
              <el-form-item prop="nickname" label="真实姓名：" :label-width="labelWidth" >
                <el-input
                  v-model="postForm.nickname"
                  placeholder="真实姓名"
                />
              </el-form-item>
              <el-form-item prop="email" label="邮箱：" :label-width="labelWidth" >
                <el-input
                  v-model="postForm.email"
                  placeholder="邮箱"
                />
              </el-form-item>
              <el-form-item prop="contactNumber" label="联系电话：" :label-width="labelWidth" >
                <el-input
                  v-model="postForm.contactNumber"
                  placeholder="联系电话"
                />
              </el-form-item>
              <el-form-item prop="password" label="密码：" :label-width="labelWidth" v-show="!isEdit">
                <el-input
                  v-model="postForm.password"
                  placeholder="密码"
                  show-password
                  :disabled="isEdit"
                />
              </el-form-item>
              <el-form-item prop="password1" label="确认密码：" :label-width="labelWidth" v-show="!isEdit">
                <el-input
                  v-model="password1"
                  placeholder="确认密码"
                  show-password
                  :disabled="isEdit"
                />
              </el-form-item>
        </el-col>
      </el-row>
    </div>
  </el-form>
</template>

<script>
// eslint-disable-next-line
/* eslint-disable */
import Cookies from 'js-cookie'
import { mapGetters } from 'vuex'
import Sticky from '../../../components/Sticky'
import Warning from './Warning'
import { createUser, updateUser, getOneUser ,listUser } from '../../../api/user'
import MarkdownEditor from '@/components/MarkdownEditor'

export default {
  components: { Sticky, Warning, MarkdownEditor },
  props: {
    isEdit: Boolean
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error(fields[rule.field] + '必须填写'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
      if (value == '' || value == undefined || value == null) {
        callback(new Error('请输入邮箱地址'))
      } else {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的邮箱地址'))
        } else {
          callback()
        }
  }
    }
    const validateContactNumber = (rule, value, callback) => {
      const reg = /^[1][1,2,3,4,5,7,8,9][0-9]{9}$/;
      if (value == '' || value == undefined || value == null) {
        callback(new Error('请输入电话号码'));
      } else {
        if ((!reg.test(value)) && value != '') {
          callback(new Error('请输入正确的电话号码'))
        } else {
          callback()
        }
  }
    }
    const validatePassword = (rule, value, callback) => {
      if(!this.isEdit){
          ////console.log(value)
        if (value === '') {
          callback(new Error('密码不能为空'))
        } else {
          callback()
        }
      } else{
        callback();
      }
      
    }
    const validatePassword1 = (rule, value, callback) => {
      ////console.log(this.password1)
      if(!this.isEdit){
       if (this.password1 === '') {
              callback(new Error('请再次输入密码'));
          } else if (this.password1 !== this.postForm.password) {
              callback(new Error('两次输入密码不一致!'));
          } else {
              callback();
          }    
      } else{
        callback();
      }
    }
    return {
      loading: false,
      postForm: {},
      fileList: [],
      fileList_enroll:[],
      listQuery: {},
      arr1:[],
      userInfo: {},
      labelWidth: '120px',
      categoryList:[],
      date_of_birth:'',
      baoming:'',
      listbaoming:[],
      password1:'',
      roleShow:false,
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        role: [{required: true, message: '请选择用户类别', trigger: 'change'}],
        nickname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        email: [{ required: true, trigger: 'change', validator: validateEmail }],
        contactNumber: [{ required: true, trigger: 'change', validator: validateContactNumber }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        password1: [{ required: true, trigger: 'blur', validator: validatePassword1 },]
      },
      post_options: [{
          value: 'admin',
          label: 'admin'
        }, {
          value: 'user',
          label: 'user'
        }],
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  created() {
    //获取用户信息
    //this.$router.push('/enroll/list')
    let usernameinfo=Cookies.get('username')
    //console.log(usernameinfo)
    this.userInfo={"username":usernameinfo}
    //判断是否是admin用户
    if(usernameinfo!='admin'){
        this.listQuery.username=usernameinfo
        this.roleShow=true
        listUser(this.listQuery).then(response => {
        ////console.log(response)
        const list = response.data.list
        this.listbaoming = list
        //console.log(this.listbaoming.length)
        this.baoming=this.roles
        ////console.log("ceshi"+this.baoming)
      })
    }
     
    if (this.isEdit) {
      const fileName = this.$route.params.fileName
      getOneUser(fileName).then(response => {
        //console.log(response)
        this.postForm=response.data
        /* let arr = response.data.photo.split(',');
        //console.log(arr)
        arr.forEach((item,index,array)=>{
            this.fileList.push({name: item, url:item})
        }) */
        //this.postForm.enroll_img=JSON.parse(this.fileList_enroll)
        
      }
   ).catch(() => {
        this.loading = false
      })
      ////console.log(fileName)
    }
  },
  methods: {
    onContentClick(data) {
      //console.log(data)
      if (data.text) {
        window.open(data.text)
      }
    },
    setDefault() {
      // this.postForm = Object.assign({}, defaultForm)
      this.fileList = []
      this.$router.push({
        path: '/user/list',
      })
      //this.postForm={state:"1"}
    },
    /* onsuccess(res){
      this.$notify({
          title: '上传个人图片成功',
          message: '上传个人图片成功',
          type: 'success',
          duration: 2000
        })
      this.fileList.push({name:res.data, url:res.data})
      this.postForm.photo=this.fileList 
    }, */
    /* onsuccess(res){
       this.$notify({
          title: '上传资料图片成功',
          message: '上传资料图片成功',
          type: 'success',
          duration: 2000
        }) 
      //let arr1 = res.data.split(',');
      //console.log(res.data) 
      this.fileList_enroll.push({name:res.data, url:res.data})
      //this.fileList.push()
      this.postForm.enroll_img=this.fileList_enroll
    }, */
   /*  submitUploadEnroll(){
        this.$refs.upload.submit();
    },
    submitUpload(){
        this.$refs.upload.submit();
    }, */
    handlePreview(file){

    },
    /* beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    }, */

    handleRemove(file, fileList) {
      this.setDefault()
    },
    getCategoryList() {
      
    },
    submitForm() {
      const onSuccess = (response) => {
        const { msg } = response
        this.$notify({
          title: '操作成功',
          message: msg,
          type: 'success',
          duration: 2000
        })
        this.loading = false
      }

      if (!this.loading) {
        this.loading = true
        //this.postForm.enroll_status="已提交"
        //this.postForm.enroll_img=JSON.stringify(this.fileList_enroll)
        ////console.log(this.fileList_enroll)
        this.$refs.postForm.validate((valid, fields) => {
          //console.log(valid, fields)
          if (valid) {
            const enroll = Object.assign({}, this.postForm)
            ////console.log(enroll)
            //let usernameinfo=Cookies.get('username')
            //this.postForm.enroll_adminuser=usernameinfo
            if (!this.isEdit) {
                  createUser(enroll).then(response => {
                  onSuccess(response)
                  this.setDefault()
                }).catch(() => {
                  this.loading = false
                })
            } else {
              updateUser(enroll).then(response => {
                onSuccess(response)
                this.setDefault()
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            const message = fields[Object.keys(fields)[0]][0].message
            this.$message({ message, type: 'error' })
            this.loading = false
          }
        })
      }
    },
    showGuide() {
      //console.log('show guide...')
    }
  }
}
</script>

<style lang="scss" scoped>
  .detail-container {
    padding: 40px 50px 20px;
    .preview-img {
      width: 200px;
      height: 270px;
    }
  }
</style>
